package com.jing.mall.product.exception;

import com.jing.mall.common.exception.SysException;
import com.jing.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@Slf4j
@RestControllerAdvice(basePackages = "com.jing.mall.product.controller")
public class productExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handvaildException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errors = new HashMap<>();
        bindingResult.getFieldErrors().forEach((error)->{
            errors.put(error.getField(),error.getDefaultMessage());
        });
        return R.error(SysException.VALID_EXCEPTION.getCode(), SysException.VALID_EXCEPTION.getMsg()).put("data",errors);
    }
    @ExceptionHandler(value = Exception.class)
    public R handException(Exception e){
        log.info("错误信息:",e);
        return R.error(SysException.UNKNOW_EXCEPTION.getCode(), SysException.UNKNOW_EXCEPTION.getMsg());
    }

}
